import {USER_CACHE,TOKEN_CACHE} from '@/utils/enums.js'
export default {
	state:{
		user:uni.getStorageSync(USER_CACHE),
		token:uni.getStorageSync(TOKEN_CACHE),
		authorities:[],
		roles:[]
	},
	mutations:{
		SET_USER(state,user){
			state.user = user
			uni.setStorageSync(USER_CACHE,user)
		},
		SET_TOKEN(state,token){
			state.token=token
			uni.setStorageSync(TOKEN_CACHE,token)
		},
		SET_AUTH(state,authorities){
			state.authorities=authorities
		},
		SET_ROLE(state,roles){
			state.roles=roles
		}
	},
	actions:{
		add_user({commit},user){
			return new Promise((resolve,reject)=>{
				this._vm.$u.api.user.login(user).then(v=>{
					const {data} = v
					//commit('SET_USER',user)
					commit('SET_TOKEN',data.token)
					resolve(data)
				}).catch(e=>{
					reject(e)
				})
			})
			
		},
		get_user({commit}){
			return new Promise((resolve,reject)=>{
				this._vm.$u.api.user.getUserInfo().then(v=>{
					const {data} = v
					commit('SET_USER',data.user)
					commit('SET_TOKEN',data.token)
					commit('SET_AUTH',data.authorities)
					commit('SET_ROLE',Array.from(new Set(data.roleNames)))
					resolve(data)
				}).catch(e=>{
					reject(e)
				})
			})
			
		},
		clear_user({commit}){
			commit('SET_USER',null)
			commit('SET_TOKEN',undefined)
			commit('SET_AUTH',[])
			uni.clearStorageSync()
		}
	},
	getters:{
		getUser(state){
			return state.user&&state.user.length>0?state.user:null
		},
		getToken(state){
			return state.token&&state.token.length>0?state.token:null
		},
		getAuth(state){
			return state.authorities&&state.authorities.length>0?state.authorities:[]
		}
	}
}